<template>
  <div class="table">
    <div class="container">
      <div class="handle-box">
        <el-button type="primary" size="mini" @click="deleteAll"
          >批量删除</el-button
        >
        &nbsp;
        <el-input
          v-model="select_word"
          size="mini"
          placeholder="请输入用户名"
          class="handle-input"
        ></el-input>
        &nbsp;
        <el-input
          v-model="select_word1"
          size="mini"
          placeholder="请输入昵称"
          class="handle-input"
        ></el-input>
        &nbsp;
        <el-input
          v-model="select_word2"
          size="mini"
          placeholder="请输入邮箱"
          class="handle-input"
        ></el-input>
        &nbsp;
        <el-input
          v-model="select_word3"
          size="mini"
          placeholder="请输入用户类型"
          class="handle-input"
        ></el-input>
        &nbsp;
        <el-button type="primary" size="mini" @click="getData"
          >查询用户</el-button
        >
        <el-button type="primary" size="mini" @click="show">添加用户</el-button>
      </div>
    </div>
    <el-table
      size="mini"
      ref="multipleTable"
      border
      style="width: 100%"
      height="680px"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column label="用户图片" width="110" align="center">
        <template slot-scope="scope">
          <div class="consumer-img">
            <img
              :src="'http://localhost:8081/blog' + scope.row.img"
              style="width: 100%"
            />
          </div>
          <el-upload
            :headers="headers"
            :action="uploadUrl(scope.row.id)"
            :show-file-list="false"
            :before-upload="beforeAvatorUpload"
            :on-success="handleAvatorSuccess"
          >
            <el-button size="mini">更新图片</el-button>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        width="120"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="nickname"
        label="昵称"
        width="120"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="email"
        label="电子邮箱"
        width="240"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="introduction"
        label="简介"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="type"
        label="类型"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column label="关注" width="80" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="getFollow(tableData[scope.$index].id)"
            >关注</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="收藏" width="80" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="getCollect(tableData[scope.$index].id)"
            >收藏</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteRow(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total,prev,pager,next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="添加新用户"
      :visible.sync="centerDialogVisible"
      width="400px"
      center
    >
      <el-form
        :model="registerForm"
        ref="registerForm"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item prop="username" label="用户名" size="mini">
          <el-input
            v-model="registerForm.username"
            placeholder="用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" size="mini">
          <el-input
            type="password"
            v-model="registerForm.password"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="昵称" size="mini">
          <el-input
            v-model="registerForm.nickname"
            placeholder="昵称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱" size="mini">
          <el-input
            v-model="registerForm.email"
            placeholder="电子邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item prop="introduction" label="简介" size="mini">
          <el-input
            v-model="registerForm.introduction"
            placeholder="简介"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="mini" @click="centerDialogVisible = false"
          >取消</el-button
        >
        <el-button size="mini" @click="addConsumer">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="修改用户"
      :visible.sync="editVisible"
      width="400px"
      center
    >
      <el-form :model="form" ref="form" label-width="80px" :rules="rules">
        <el-form-item prop="username" label="用户名" size="mini">
          <el-input v-model="form.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" size="mini">
          <el-input
            type="password"
            v-model="form.password"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="昵称" size="mini">
          <el-input v-model="form.nickname" placeholder="昵称"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱" size="mini">
          <el-input v-model="form.email" placeholder="电子邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="introduction" label="简介" size="mini">
          <el-input v-model="form.introduction" placeholder="简介"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="mini" @click="editVisible = false">取消</el-button>
        <el-button size="mini" @click="editSave">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      centerDialogVisible: false, //添加弹窗是否显示
      editVisible: false, //编辑弹窗是否显示
      registerForm: {
        //添加框
        username: "",
        password: "",
        nickname: "",
        email: "",
        introduction: "",
      },
      form: {
        //编辑框
        id: "",
        username: "",
        password: "",
        nickname: "",
        email: "",
        introduction: "",
      },
      tableData: [],
      tempData: [],
      select_word: "",
      select_word1: "",
      select_word2: "",
      select_word3: "",
      pageSize: 5, //分页每页大小
      currentPage: 1, //当前页
      total: 0,
      idx: -1, //当前选择项
      multipleSelection: [], //哪些项已经打勾
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 4, max: 30, message: "长度在 4 到 30 个字符" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        nickname: [
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入电子邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的电子邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  created() {
    this.getData();
  },
  computed: {
    headers() {
      return { Authorization: sessionStorage.getItem("tokenStr") };
    },
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    resetForm() {
      this.registerForm = {};
    },
    show() {
      this.resetForm();
      this.centerDialogVisible = true;
    },
    //获取当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getData();
    },
    //查询所有用户
    getData() {
      this.tempData = [];
      this.tableData = [];
      let param =
        "user/" +
        this.currentPage +
        "/" +
        this.pageSize +
        "?username=" +
        this.select_word +
        "&nickname=" +
        this.select_word1 +
        "&email=" +
        this.select_word2 +
        "&type=" +
        this.select_word3;
      this.$get(param).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.records;
          this.tempData = res.data.records;
          this.total = res.data.total;
        }
      });
    },
    //添加用户
    addConsumer() {
      this.$refs["registerForm"].validate((valid) => {
        if (valid) {
          let params = {
            username: this.registerForm.username,
            password: this.registerForm.password,
            nickname: this.registerForm.nickname,
            email: this.registerForm.email,
            introduction: this.registerForm.introduction,
          };
          this.$post("user", params).then((res) => {
            if (res.code == 200) {
              this.getData();
              this.centerDialogVisible = false;
            }
          });
        } else {
          this.$message.error("数据校验失败，请检查!", "error");
        }
      });
    },
    //弹出编辑页面
    handleEdit(row) {
      this.editVisible = true;
      this.form = {
        id: row.id,
        username: row.username,
        password: row.password,
        nickname: row.nickname,
        email: row.email,
        introduction: row.introduction,
      };
    },
    //保存编辑页面修改的数据
    editSave() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let params = {
            id: this.form.id,
            username: this.form.username,
            password: this.form.password,
            nickname: this.form.nickname,
            email: this.form.email,
            introduction: this.form.introduction,
          };
          this.$put("user", params).then((res) => {
            if (res.code == 200) {
              this.getData();
              this.editVisible = false;
            }
          });
        } else {
          this.$message.error("数据校验失败，请检查!", "error");
        }
      });
    },
    //更新图片
    uploadUrl(id) {
      return `http://localhost:8081/blog/user/pic/${id}`;
    },
    //删除一名用户
    deleteRow(val) {
      this.$confirm("您确定要删除吗？", "提示", {
        type: "warning",
      }).then(() => {
        this.$delete("user/" + val).then((res) => {
          if (res.code == 200) {
            this.getData();
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    deleteAll() {
      this.$confirm("您确定要删除吗？", "提示", {
        type: "warning",
      }).then(() => {
        for (var i = 0; i < this.multipleSelection.length; i++) {
          this.$delete("user/" + this.multipleSelection[i].id).then((res) => {
            if (res.code == 200) {
              this.getData();
            } else {
              this.$message.error(res.message);
            }
          });
        }
      });
    },
    beforeAvatorUpload(file) {
      var testMsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (testMsg != "jpg" && testMsg != "jpeg" && testMsg != "png") {
        this.$message({
          message: "上传文件只能是jpg、jpeg、png格式",
          type: "error",
        });
        return false;
      }
      return true;
    },
    handleAvatorSuccess(res) {
      if (res.code == 200) {
        this.$message.success(res.message);
      } else {
        this.$message.error(res.message);
      }
    },
    //转向该用户的收藏列表
    getCollect(id) {
      this.$router.push({ path: "/home/collect", query: { id } });
    },
    getFollow(id) {
      this.$router.push({ path: "/home/follow", query: { id } });
    },
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
  float: left;
}
.consumer-img {
  width: 100%;
  height: 80px;
  border-radius: 5px;
  margin-bottom: 5px;
  overflow: hidden;
}
.handle-input {
  width: 250px;
  display: inline-block;
}
.pagination {
  display: flex;
  justify-content: center;
}
</style>